package edu.cs.usask.ca.silver.plugin.rcp.editors;

import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;

import edu.cs.usask.ca.silver.businesslogic.ids.ParameterID;
import edu.cs.usask.ca.silver.plugin.rcp.dao.SilverBusinessLogicController;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;

/**
 * This class led functionality to edit the data being stored in the various
 * table viewers thought the editors panes and the add new scenario dialog
 * window. This appropriate columns are allowed this support for a given table
 * viewer.
 * 
 * @author Mike Taylor
 * 
 */

public class InfoEditorEditingSupport extends EditingSupport {

	private final CellEditor editor;
	private final String columnName;
	private final InfoEditor infoEditor;
	private static Logger logger = Logger
			.getLogger(InfoEditorEditingSupport.class);

	/**
	 * Constructor
	 * 
	 * @param viewer
	 *            table viewer that the column belongs to
	 * @param columnName
	 *            the String name for the column that is editable
	 * @param infoEditor
	 */
	public InfoEditorEditingSupport(ColumnViewer viewer, String columnName,
			InfoEditor infoEditor) {
		super(viewer);
		editor = new TextCellEditor(((TableViewer) viewer).getTable());
		this.columnName = columnName;
		this.infoEditor = infoEditor;
	}

	@Override
	protected boolean canEdit(Object element) {
		return true;
	}

	/**
	 * get the cell to edited
	 */
	@Override
	protected CellEditor getCellEditor(Object element) {
		return editor;
	}

	/**
	 * get the data that is edited
	 */
	@Override
	protected Object getValue(Object element) {
		// TODO strictly trying to get parameter units editable
		try {
			return SilverBusinessLogicController.borrowParameterObject()
					.getUnits((ParameterID) element,
							infoEditor.getAssociatedStorage());
		} catch (Exception e) {
			LoggerReportScheduler.scheduleErrorLogging(logger,"error while getting unit for parameter id", e);
		}
		return null;
	}

	/**
	 * set information in the database to reflect the changes that have been
	 * made within the table viewer.
	 */
	@Override
	protected void setValue(Object element, Object value) {
		assert (element instanceof ParameterID);
		assert (value instanceof String);

		try {
			SilverBusinessLogicController.borrowParameterObject().setUnits(
					(ParameterID) element, (String) value,
					infoEditor.getAssociatedStorage());
		} catch (Exception e) {
			LoggerReportScheduler.scheduleErrorLogging(logger,"error while setting unit for parameter id", e);
		}

		getViewer().update(element, null);

	}

}/* end of class */
